﻿using System.Data.SQLite;
using System.IO;
using Vkontakte.Api.Database;

namespace VkClientIM.Database
{
	public sealed class ImageCache
		:IImageCache
	{
		private SQLiteConnection _sql;

		public ImageCache(string filename)
		{
			var builder = new SQLiteConnectionStringBuilder
			{
				BinaryGUID = true,
				DataSource = filename
			};
			string connectionString=builder.ToString();
			_sql=new SQLiteConnection(connectionString);
			_sql.Open();
		}

		~ImageCache()
		{
			if (_sql!=null)
			{
				_sql.Close();
				_sql = null;
			}
		}


		private int CreateTables()
		{
			var command= _sql.CreateCommand();
			command.CommandText = "CREATE TABLE [ImageCache] ([Url] NVARCHAR(200) UNIQUE NOT NULL,[Image] BLOB NOT NULL)";
			return command.ExecuteNonQuery();
		}

		public static ImageCache OpenOrCreate(string filename)
		{
			if (File.Exists(filename))
			{
				return new ImageCache(filename);
			}
			else
			{
				ImageCache ret = new ImageCache(filename);
				ret.CreateTables();
				return ret;
			}
		}


		public void SaveImage(string url, byte[] image)
		{
			SQLiteCommand command= _sql.CreateCommand();
			command.CommandText = "INSERT INTO [ImageCache] VALUES (@url,@image)";
			SQLiteParameter p_url = new SQLiteParameter("@url");
			SQLiteParameter p_image = new SQLiteParameter("@image");
			command.Parameters.Add(p_url);
			command.Parameters.Add(p_image);
			p_url.Value = url;
			p_image.Value = image;
			command.ExecuteNonQuery();
		}

		public byte[] GetImage(string url)
		{
			SQLiteCommand command = _sql.CreateCommand();
			command.CommandText = string.Format("SELECT [Image] FROM [ImageCache] WHERE [Url]='{0}'", url);

			object o= command.ExecuteScalar();
			return o as byte[];
		}

		public bool IsCached(string url)
		{
			SQLiteCommand command = _sql.CreateCommand();
			command.CommandText = string.Format("SELECT COUNT(*) FROM [ImageCache] WHERE [Url]='{0}'", url);

			object o = command.ExecuteScalar();
			return ((long) o) != 0;
		}
	}
}
